var listColumns = [[
    {field: "id", checkbox: true},
    {field: "title", title: "一级菜单", align: "center", width: 100},
    {field: "tag", title: "二级菜单", align: "center", width: 120},
    {field: "comment", title: "文件路径", align: "center", width: 450},
    {field: "createTime", title: "创建时间", align: "center", width: 140},
    {
        field: "handle", title: "操作", align: "center", width: 120, formatter: function (value, rowData,index) {
            var roleId = $("#session_roleId").val();
            if(roleId == 2 || roleId==4){
                return '<a class="layui-btn layui-btn-xs"  onclick="editData('+index+')">编辑</a>' +
                    '<a class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteData('+rowData.id+')" style="text-decoration: none">删除</a>'
            }
            return "";
    }
    }
]];

layui.config({
    base: "../static/agent-ui/js/"
});

$.fn.toJSON = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        var name = this.name;
        var value = this.value;
        var paths = this.name.split(".");
        var len = paths.length;
        var obj = o;
        $.each(paths, function (i, e) {
            if (i == len - 1) {
                if (obj[e]) {
                    if (!obj[e].push) {
                        obj[e] = [obj[e]];
                    }
                    obj[e].push(value || '');
                } else {
                    obj[e] = value || '';
                }
            } else {
                if (!obj[e]) {
                    obj[e] = {};
                }
            }
            obj = o[e];
        });
    });
    return o;
};

layui.use(["laypage", "layer", "validator", "tools", "form", "select", "laydate", "upload"], function () {
    var form = layui.form;
    var date = layui.laydate;
    date.render({
        elem: '#ringTime',
        type: 'datetime',
        range: true
    });


    var layer=layui.layer;

    $(function () {
        $('#list').datagrid({
            columns: listColumns,
            fitColumns: false,
            fit: true,
            singleSelect: true,
            pagination: true,
            pageSize: 30,
            pageList: [30, 50, 100, 1000],
            toolbar: '#receivedListHeader',
            method: 'get',
            url: ctx +'/knowledge/list',
            onLoadSuccess: function () {
            }
        });
    });

    $('#search_submit').on('click', function () {
        $('#list').datagrid('load', $('#search_form').toJSON());
    });

    $("#addData").on("click", function(){
        /* 再弹出添加界面 */
        layer.open({
            type:1,
            title:"添加",
            skin:"myclass",
            area:["50%"],
            content:$("#add").html(),
            success:function (layero,index) {
                form.render();
                layero.addClass('layui-form');
                layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
                uploadRender(layero);
            },
            btn:['提交','关闭'],
            yes:function (index,layero) {
                form.on('submit(fromContent)', function (data) {
                    add(index,'1',layero)
                });
            },
            btn2:function (index,layero) {
                layer.close(index);
            }
        });

    });
});
function add(index,status,layero) {
    var title = $(layero).find('input[name=title]').val();
    var tag = $(layero).find('input[name=tag]').val();
    var comment = $(layero).find('input[name=comment]').val();
    $.ajax({
        url:ctx+'/knowledge/insert',
        type : 'POST',
        data:
            {title:title,
                tag:tag,
                comment:comment
        },
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: json.msg
            });

        }
    });
}

//普通图片上传
function uploadRender(layero) {
    var $ = layui.jquery
        , upload = layui.upload;
    layui.each(layero.find("#btn1"),function (index,elem) {
        var uploadInst = upload.render({
            elem: elem,
            accept: 'file'
            , url: ctx + '/picWord/upload/'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                /*obj.preview(function (index, file, result) {
                    layero.find('#img1').attr('src', result); //图片链接（base64）
                });*/
            }
            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                $(layero).find('input[name=comment]').val(res.picUrl);
                //上传成功
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
    })
}

function deleteData(id) {
    layer.confirm('是否确认删除！', {
        btn: ['删除','关闭'] //按钮
    }, function(index){
        $.ajax({
            url:ctx+'/knowledge/delete/'+id,
            type : 'GET',
            success: function(result){
                var layer = layui.layer;
                var json = JSON.parse(result);
                if(json.code=='0'){
                    layer.close(index);
                    $('#list').datagrid('reload');
                }else{
                    layer.open({
                        title: '报错了'
                        ,content: json.msg
                    });
                }
            },
            error: function(result){
                var json = JSON.parse(result);
                var layer = layui.layer;
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }
        });
    }, function(index){
        layer.close(index);
    });
}

// 编辑
function  editData(index) {
    var rows = $('#list').datagrid('getRows');
    var json = rows[index];
    var form = layui.form;
    layer.open({
        type:1,
        title:"编辑",
        skin:"myclass",
        area:["50%"],
        content:$("#add").html(),
        success:function (layero,index) {
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            $(layero).find('input[name=title]').val(json.title);
            $(layero).find('input[name=tag]').val(json.tag);
            $(layero).find('input[name=comment]').val(json.comment);
            uploadRender(layero);
        },
        btn:['提交','关闭'],
        yes:function (index,layero) {
            form.on('submit(fromContent)', function (data) {
                update(index,json.id,layero)
            });
        },
        btn2:function (index,layero) {
            layer.close(index);
        }
    });
}
function update(index,id,layero) {
    var title = $(layero).find('input[name=title]').val();
    var tag = $(layero).find('input[name=tag]').val();
    var comment = $(layero).find('input[name=comment]').val();
    $.ajax({
        url:ctx+'/knowledge/update',
        type : 'POST',
        data:
            {title:title,
                tag:tag,
                comment:comment,
                id:id
            },
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: json.msg
            });

        }
    });
}




